import 'dart:io';
import 'dart:ui';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/network/file_preview_http.dart';
import 'package:kq_flutter_core_widget/utils/file_util.dart';
import 'package:kq_flutter_core_widget/utils/native/file_unicode_native_util.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'state.dart';

class FilePreviewController extends GetxController {
  final FilePreviewState state = FilePreviewState();

  final WebViewController webController = WebViewController();

  @override
  void onInit() async {
    super.onInit();

    String fileName = Get.arguments['fileName'];
    String url = Get.arguments['url'];
    if (Platform.isIOS) {
      if (isTxtFile(fileName)) {
        var dir = await FileUtil.getTempDownloadPath();
        var filePath = await FilePreviewHttp.downloadFile(url, dir, fileName,
            (count, total) {
          state.showProgress = true;
          state.progress = count * 100.0 / total;
          update();
        });
        state.showProgress = false;
        if (filePath != null) {
          //下载成功,去原生进行编码处理
          var fileContent = await FileUnicodeNativeUtil.fileUnicode(filePath);
          state.useWebView = true;
          if (fileContent != null) {
            state.status = FilePreviewStatus.success;
            update();
            load(fileContent, isLoadHTMLString: true);
          }
        } else {
          //下载失败
          state.status = FilePreviewStatus.failed;
          update();
        }
      } else if (isPdfFile(fileName)) {
        var dir = await FileUtil.getTempDownloadPath();
        var filePath = await FilePreviewHttp.downloadFile(url, dir, fileName,
            (count, total) {
          state.showProgress = true;
          state.progress = count * 100.0 / total;
          update();
        });
        state.showProgress = false;
        if (filePath != null) {
          state.status = FilePreviewStatus.success;
          state.useWebView = true;
          update();
          load(filePath);
        } else {
          //下载失败
          state.status = FilePreviewStatus.failed;
          update();
        }
      } else {
        state.status = FilePreviewStatus.success;
        state.useWebView = true;
        update();
        load(url);
      }
    } else if (canOpenWithWps(fileName)) {
      var wpsUrl = await FilePreviewHttp.getWpsUrl(url, fileName);
      if (wpsUrl != null) {
        state.status = FilePreviewStatus.success;
        state.useWebView = true;
        update();
        load(wpsUrl);
      } else {
        state.status = FilePreviewStatus.failed;
        update();
      }
    } else if (isTxtFile(fileName)) {
      //下载下来本地处理，比如txt
      var dir = await FileUtil.getTempDownloadPath();
      var filePath = await FilePreviewHttp.downloadFile(url, dir, fileName,
          (count, total) {
        state.showProgress = true;
        state.progress = count * 100.0 / total;
        update();
      });
      state.showProgress = false;
      if (filePath != null) {
        //下载成功
        var string = await FileUtil.readFileAsString(filePath);
        state.txtContent = string;
        state.status = FilePreviewStatus.success;
        update();
      } else {
        //下载失败
        state.status = FilePreviewStatus.failed;
        update();
      }
    } else {
      //不支持的打开的文件
      state.status = FilePreviewStatus.notSupport;
      update();
    }
  }

  /// 是不是纯文本文件
  bool isTxtFile(String fileName) {
    return fileName.toLowerCase().endsWith(".txt") ||
        fileName.toLowerCase().endsWith(".json") ||
        fileName.toLowerCase().endsWith(".html") ||
        fileName.toLowerCase().endsWith(".java") ||
        fileName.toLowerCase().endsWith(".xml");
  }

  /// 是不是pdf文件
  bool isPdfFile(String fileName) {
    return fileName.toLowerCase().endsWith(".pdf");
  }

  /// 能否用wps打包
  bool canOpenWithWps(String fileName) {
    return fileName.toLowerCase().endsWith(".xls") ||
        fileName.toLowerCase().endsWith(".xlsx") ||
        fileName.toLowerCase().endsWith(".pdf") ||
        fileName.toLowerCase().endsWith(".doc") ||
        fileName.toLowerCase().endsWith(".docx") ||
        fileName.toLowerCase().endsWith(".csv") ||
        fileName.toLowerCase().endsWith(".pptx") ||
        fileName.toLowerCase().endsWith(".ppt");
  }

  load(String url, {bool? isLoadHTMLString}) {
    var web = webController
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            state.progress = progress.toDouble();
            update();
          },
          onPageStarted: (String url) {
            state.showProgress = true;
            update();
          },
          onPageFinished: (String url) {
            state.showProgress = false;
            state.status = FilePreviewStatus.success;
            update();
          },
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      );
    if (isLoadHTMLString != null && isLoadHTMLString == true) {
      web.loadHtmlString(url);
    } else {
      web.loadRequest(url.contains('http://') || url.contains('https://')
          ? Uri.parse(url)
          : Uri.file(url));
    }
  }
}
